<?php

abstract class BaseDao {
	private $_queryHelper = null;
	
	protected $connection = null;
	protected $cache = null;
	
	/**
	 * @return PDO
	 */
	abstract public function getConnection();
	
	public function setConnection($conn) {
		$this->connection = $conn;
	}
	
	/**
	 * @return QueryHelper
	 */
	public function queryHelper() {
		if (!$this->_queryHelper) {
			require_once 'FModel/Common/Dao/QueryHelper.php';
			$this->_queryHelper = new QueryHelper($this->getConnection());
		}
		return $this->_queryHelper;
	}
	
	public function getUpdateSect(Array $array) {
		$updateSect = ' SET ';
		foreach (array_keys($array) as $key) {
			$updateSect .= '`' . $key . '`=:' . $key . ',';
		}
		return substr_replace($updateSect, '', -1);
	}
	
	public function getInsertClause(Array $data) {
		$fields = ' (';
		$values = ' VALUES (';
		foreach (array_keys($data) as $key) {
			$fields = $fields . '`' . $key . '`,';
			$values = $values . ':' . $key . ',';
		}
		$fields = substr_replace($fields, ')', -1);
		$values = substr_replace($values, ')', -1);
		
		return $fields . $values;
	}
	
	public function bindValues($stmt, $array) {
		foreach ($array as $key => $value) {
			$stmt->bindValue(':' . $key, $value);
		}
	}
	
	public function getOffset($pageNumber, $numberPerPage) {
		return ($pageNumber - 1) * $numberPerPage;
	}
	
	public function getImplodeString($dataArr) {
		if (!is_array($dataArr)) return $this->getConnection()->quote($dataArr);
		if (!count($dataArr)) return "''";
		$imploded = array();
		foreach ($dataArr as $value) {
			$imploded[] = $this->getConnection()->quote($value);
		}
		return implode(", ", $imploded);
	}
}

